#include "TimeEventManager.h"
#include <hgl/type/DateTime.h>

TimeEvent::TimeEvent(double time)
:triger_time(time)
{

}

bool TimeObject::Update(double cur_time)
{
	if(cur_time < triger_time)
		return (false);
	
	if(triger_time == 0)
		triger_time = CreateStandardTime(cur_time);
	
	if(!OnEvent(cur_time))
		return (false);
	
	if(interval_time != 0)
		triger_time += (int64)((cur_time - triger_time) / interval_time) * interval_time + interval_time;
	
	LOG_INFO(OS_TEXT("TimeObject::Update() cur_time = ") + OSString(cur_time) + OS_TEXT(",triger_time = ") + OSString(triger_time) + OS_TEXT(",interval_time =") + OSString(interval_time));
	return (true);
}

bool TimeEventManager::AddEvent(const TimeEventAdapter& event)
{
	mutex.Lock();
	event_list.Add(event);
	mutex.Unlock();
}

bool TimeEventManager::DeleteEvent(const TimeEventAdapter& event)
{
	mutex.Lock();
	event_list.Delete(event);
	mutex.Unlock();
}


bool TimeEventManager::Update(double cur_time)
{
	if(is_update)
		return (true);
	
	if(!mutex.TryLock())
		return (true);
	
	if(is_update)
	{
		mutex.Unlock();
		return (true);
	}
	
	is_update = true;
	
	mutex.Unlock();
	
	TimeEvent *event;
	int32 event_count = event_list. Count();
	for(int32 i = 0;i < event_count;i++)
	{
		event = event_list. Data()-> TimeEvent();
		
		if(!event)
		{
			LOG_ERROR("TimeEventManager::A SERIOUS EVENT OCCUR");
			break;
		}
		
		if(cur_time >= event-> TrigetTime())
		{
			event->OnEvent(cur_time);
			DeleteEvent(event);
			SAFE_CLEAR(event);
			LOG_INFO(OS_TEXT("TimeEventManager::Update count =") + OSString(event_list. Count()));
		}else
			break;
	}
	is_update = false;
	return (true);
}

TimeEventManager time_event_mananger;